package com.bringway.p2p.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bringway.global.controller.JsonController;
import com.bringway.global.domain.SysUserDetails;
import com.bringway.global.domain.Tree;
import com.bringway.global.domain.TreeNode;
import com.bringway.global.service.MenuService;
import com.bringway.global.util.RequestUtils;
import com.bringway.p2p.service.MenuCUDService;

import net.sf.json.JSONObject;

/*
 * @author qjy
 * @className MenuController
 * @description 菜单的增删改控制器
 * @date 2015年12月14日下午6:33:05
 */
@Controller
@RequestMapping("/cud")
public class P2PMenuController extends JsonController {
	@Autowired
	private MenuCUDService menuCudService;

	@Autowired
	private MenuService menuService;

	/**
	 * @方法名称:addMenu
	 * @方法描述:菜单添加
	 * @author fan
	 * @date 2015年12月14日下午6:37:22
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/addMenu")
	public ModelAndView addMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		result.put("success", true);
		String name = RequestUtils.getStringParameter(request, "name");
		String parent_id = RequestUtils.getStringParameter(request, "parent_id");
		String url = RequestUtils.getStringParameter(request, "url");
		String px = RequestUtils.getStringParameter(request, "px");
		String params = RequestUtils.getStringParameter(request, "params");
		String icon = RequestUtils.getStringParameter(request, "icon");
		/*
		 * if (Integer.valueOf(px) <= 0) { result.put("isAddSuc", false);
		 * result.put("msg", "排序值必须大于0!"); serialize(request, response, result);
		 * return null; }
		 */
		JSONObject parms = new JSONObject();
		parms.put("name", name);
		parms.put("parent_id", parent_id);
		parms.put("url", url);
		parms.put("px", px);
		parms.put("icon", icon);
		parms.put("params", params);
		boolean bool = menuCudService.addMenu(parms);
		result.put("isAddSuc", bool);
		serialize(request, response, result);
		return null;
	}

	/**
	 * @方法名称:deleteMenu
	 * @方法描述:删除菜单的方法
	 * @author qjy
	 * @date 2015年12月15日下午1:35:32
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/deleteMenu")
	public ModelAndView deleteMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int id = RequestUtils.getIntParameter(request, "id", 0);
		JSONObject parms = new JSONObject();
		parms.put("id", id);
		boolean bool = menuCudService.deleteMenu(parms);
		JSONObject result = new JSONObject();
		result.put("success", true);
		serialize(request, response, result);
		return null;
	}

	/**
	 * @方法名称:updateMenu
	 * @方法描述:修改菜单的方法
	 * @author qjy
	 * @date 2015年12月16日上午9:29:20
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateMenu")
	public ModelAndView updateMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		result.put("success", true);
		String name = RequestUtils.getStringParameter(request, "name");
		String url = RequestUtils.getStringParameter(request, "url");
		String parent_id = RequestUtils.getStringParameter(request, "parent_id");
		int id = RequestUtils.getIntParameter(request, "id");
		String px = RequestUtils.getStringParameter(request, "px", "0");
		String params = RequestUtils.getStringParameter(request, "params");
		String icon = RequestUtils.getStringParameter(request, "icon");
		if (Integer.valueOf(px) <= 0) {
			result.put("isUpdate", false);
			result.put("msg", "排序值必须大于0!");
			serialize(request, response, result);
			return null;
		}
		JSONObject parms = new JSONObject();
		parms.put("name", name);
		parms.put("url", url);
		parms.put("parent_id", parent_id);
		parms.put("id", id);
		parms.put("params", params);
		parms.put("px", px);
		parms.put("icon", icon);
		boolean bool = menuCudService.updateMenu(parms);
		result.put("isUpdate", bool);
		serialize(request, response, result);
		return null;
	}

	/**
	 * @方法名称:queryUserByRoleId
	 * @方法描述:根据roleId查询user
	 * @author qjy
	 * @date 2015年12月22日上午10:49:57
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryUserByRoleId")
	public ModelAndView queryUserByRoleId(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String roleId = RequestUtils.getStringParameter(request, "roleId");
		String XM = RequestUtils.getStringParameter(request, "xm");
		String GWMC = RequestUtils.getStringParameter(request, "gwmc");
		String GYH = RequestUtils.getStringParameter(request, "gyh");
		Integer curpage = RequestUtils.getIntParameter(request, "start");
		Integer pageSize = RequestUtils.getIntParameter(request, "limit");
		Integer page = RequestUtils.getIntParameter(request, "page");// 新版本,传参
		if (null != page) {// 新版本,传参
			curpage = (page - 1) * pageSize;
		}
		JSONObject parms = new JSONObject();
		JSONObject result = new JSONObject();
		parms.put("ROLE_ID", roleId);
		parms.put("XM", XM);
		parms.put("GWMC", GWMC);
		parms.put("GYH", GYH);
		parms.put("curpage", curpage);
		parms.put("pageSize", pageSize);
		Map<String, Object> map = menuCudService.queryUser(parms);
		result.put("data", map.get("userList"));
		result.put("total", map.get("total"));
		if (null != page) {// 新版本,传参
			int count = MapUtils.getIntValue(map, "total");
			int totalPage = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
			result.put("totalPage", totalPage);
		}
		serialize(request, response, result);
		return null;
	}

	/**
	 * @方法名称:queryMenuList
	 * @方法描述:查询菜单列表---根据父级id，并且根据userid判断复选框是否点选
	 * @author qjy
	 * @date 2015年12月23日下午2:59:49
	 * @return
	 */
	@RequestMapping("/queryMenuList")
	public ModelAndView queryMenuList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysUserDetails sysUserDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		JSONObject params = new JSONObject();
		String nodeId = request.getParameter("nodeId");
		if (StringUtils.isEmpty(nodeId)) {
			nodeId = "-1";
		}
		params.put("nodeId", nodeId);
		params.put("roleId", sysUserDetails.getRoleId());
		params.put("gyh", sysUserDetails.getGyh());
		List<Map<String, Object>> list = menuCudService.listMenuByParent(params);
		// 定义一个list ，用来存储应该被选中的菜单的id
		List list2 = new ArrayList();
		String userId = RequestUtils.getStringParameter(request, "userId");
		params.clear();
		params.put("userId", userId);
		list2 = menuCudService.queryMenuIdsByUserId(params);
		// 处理返回结果
		ArrayList nodeList = new ArrayList();
		Iterator iter = list.iterator();
		while (iter.hasNext()) {
			Map map = (Map) iter.next();
			Tree n = new Tree();
			// 如果list2中包含了这个id，那么就将这个checkbox选中
			if (list2.contains(map.get("ID").toString())) {
				n.setChecked(true);
			}
			iter.remove();
			n.setAsync(true);
			n.setText(map.get("NAME").toString());
			n.setId(map.get("ID").toString());
			n.setUrl(map.get("URL").toString());
			n.setChildct(map.get("CHILDCT").toString());
			nodeList.add(n);
		}
		serialize(request, response, nodeList, true);
		return null;
	}

	/**
	 * @方法名称:saveUserMenu
	 * @方法描述:保存最新的user与msenu之间的关系
	 * @author qjy
	 * @date 2015年12月24日下午4:52:23
	 * @return
	 */
	@RequestMapping("/saveUserMenu")
	public ModelAndView saveUserMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String[] strings = null;
		String menuIds = RequestUtils.getStringParameter(request, "menuIds");
		if (StringUtils.isNotEmpty(menuIds)) {// 新版
			strings = menuIds.split(",");
		} else {
			strings = RequestUtils.getRequiredStringParameters(request, "menuids");// 老版
		}
		String userId = RequestUtils.getStringParameter(request, "userId");
		JSONObject parms = new JSONObject();
		JSONObject result = new JSONObject();
		parms.put("menuIds", strings);
		parms.put("userId", userId);
		boolean bool = menuCudService.saveMenuUserLink(parms);
		result.put("success", true);
		result.put("isUpdate", bool);
		serialize(request, response, result);
		return null;
	}

	/**
	 * @方法名称:queryMenuListWithOutCheckBox
	 * @方法描述:查询所有的菜单(没有checkbox)
	 * @author qjy
	 * @date 2016年1月4日上午9:40:54
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryMenuListWithOutCheckBox")
	public ModelAndView queryMenuListWithOutCheckBox(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		SysUserDetails sysUserDetails = (SysUserDetails) SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		JSONObject params = new JSONObject();
		String nodeId = request.getParameter("nodeId");
		if (StringUtils.isEmpty(nodeId)) {
			nodeId = "-1";
		}
		params.put("nodeId", nodeId);
		params.put("roleId", sysUserDetails.getRoleId());
		params.put("gyh", sysUserDetails.getGyh());
		List<Map<String, Object>> list = menuCudService.listMenuByParent(params);
		ArrayList list2 = new ArrayList();
		Iterator iterator = list.iterator();
		while (iterator.hasNext()) {
			Map<String, Object> map = (Map) iterator.next();
			iterator.remove();
			TreeNode treeNode = new TreeNode();
			treeNode.setAsync(true);
			treeNode.setText(map.get("NAME").toString());
			treeNode.setId(map.get("ID").toString());
			treeNode.setUrl(map.get("URL").toString());
			treeNode.setPx(map.get("ORDER_NUM").toString());
			treeNode.setChildct(map.get("CHILDCT").toString());
			treeNode.setIcon_num(MapUtils.getString(map, "ICON_NUM"));
			list2.add(treeNode);
		}
		serialize(request, response, list2, true);
		return null;
	}

	/**
	 * 
	 * @方法名称: queryMenuRoleList
	 * @方法描述: 查询角色菜单
	 * @时间:2016年2月25日下午6:47:46
	 * @author:qjy
	 * @param requeset
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryMenuRoleList")
	public ModelAndView queryMenuRoleList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String menuId = RequestUtils.getStringParameter(request, "menuId");
		JSONObject params = new JSONObject();
		params.put("menuId", menuId);
		List list = menuCudService.queryMenuRoleList(params);
		JSONObject result = new JSONObject();
		result.put("data", list);
		serialize(request, response, result);
		return null;
	}

	/**
	 * @方法名称: addMenuRoleRelatinShip
	 * @方法描述: 添加角色菜单关系
	 * @时间:2016年2月25日下午7:15:35
	 * @author:qjy
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addMenuRoleRelatinShip")
	public ModelAndView addMenuRoleRelatinShip(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String menuId = RequestUtils.getStringParameter(request, "menuId");
		String menuRoleIds = RequestUtils.getStringParameter(request, "menuRoleIds");
		String menuRoleNames = RequestUtils.getStringParameter(request, "menuRoleNames");

		JSONObject params = new JSONObject();
		params.put("menuId", menuId);
		params.put("menuRoleIds", menuRoleIds);
		params.put("menuRoleNames", menuRoleNames);
		boolean bool = menuCudService.MenuRoleRelatinShipSave(params);
		JSONObject result = new JSONObject();
		result.put("success", true);
		result.put("isAdd", bool);
		serialize(request, response, result);
		return null;
	}

}
